<template>
  <div class="mainsu">
    <div class="main_spac1">
      <div class="main_white padding10">
        <div class="mainor_form small-top">
          <el-form
            :inline="true"
            :model="form"
            class="demo-form-inline"
            ref="userListFrom"
            label-width="80px"
             id="form"
          >
            <el-form-item label="盘点日期：" prop="createTime">
              <el-date-picker
                v-model="createTime"
                type="daterange"
                class="time220"
                :editable="false"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                :clearable="false"
                :picker-options="pickerOptions"
                @change="getArticleList"
              />
            </el-form-item>
            <el-form-item label="盘点单号：" prop="order_sn">
              <el-input
                v-model.trim="form.order_sn"
                placeholder="盘点单号"
                clearable
                class="wid220"
              ></el-input>
            </el-form-item>
            <MainFormBtn @reset="reset" @getSearchFor="getArticleList" :loading="listLoading" :showBtn="false">
              <el-button @click="importDialog">导入</el-button>
            </MainFormBtn>
          </el-form>
        </div>
        <div class="main-controls-wrap">
          <div>
            <el-button>
              <router-link to="/warehouse/check/quick"> 快捷盘点</router-link>
            </el-button>
            <el-button>
              <router-link to="/warehouse/check/add"> 创建盘点单 </router-link>
            </el-button>
            <el-button @click="exportCheck">导出</el-button>
          </div>
        </div>
        <div class="main_table">
          <el-table
            ref="multipleTable"
            v-loading="listLoading"
            :data="list.list.data"
            element-loading-text="加载中"
            fit
            border
            highlight-current-row
            :header-cell-class-name="this.$verticaline"
            :height="borderHeight"
            :header-cell-style="tableHeightStyle"
            @header-dragend="changeTableWidth"
            @row-dblclick="rowDblclick"
          >
            <el-table-column
              label="盘点单号"
              prop="order_sn"
              :width="tableWidth[hash + 'order_sn']"
            />
            <el-table-column
              label="盘损金额"
              prop="debt_money"
              :width="tableWidth[hash + 'debt_money']"
            />
            <el-table-column
              label="盘溢金额"
              prop="overflow_money"
              :width="tableWidth[hash + 'overflow_money']"
            />
            <el-table-column
              label="状态"
              prop="status"
              :width="tableWidth[hash + 'status']"
            >
              <template slot-scope="scope"
                ><span :class="'order' + scope.row.status">
                  {{ list.statusList[scope.row.status] }}</span
                ></template
              >
            </el-table-column>

            <el-table-column
              label="创建时间"
              prop="created_at"
              :width="tableWidth[hash + 'created_at']"
            >
              <template slot-scope="scope">{{
                parseTime(scope.row.created_at, "{y}-{m}-{d}")
              }}</template>
            </el-table-column>

            <el-table-column
              label="盘点时间"
              prop="updated_at"
              :width="tableWidth[hash + 'updated_at']"
            >
              <template slot-scope="scope">{{
                scope.row.inventory_time
                  ? parseTime(scope.row.inventory_time, "{y}-{m}-{d}")
                  : ""
              }}</template>
            </el-table-column>
            <el-table-column
              label="管理操作"
              align="left"
              fixed="right"
              prop="operate"
              :width="tableWidth[hash + 'operate'] || 240"
              class-name="main_hei"
              label-class-name="main-center"
            >
              <template slot-scope="scope">
                <router-link :to="'/warehouse/check/see/' + scope.row.id">
                  <el-link type="success">查看</el-link>
                </router-link>

                <router-link :to="'/warehouse/check/edit/' + scope.row.id">
                  <el-link type="warning" v-if="scope.row.status == 0"
                    >审核</el-link
                  >
                </router-link>
                <!-- <el-link>打印</el-link> -->
                <el-link
                  v-if="scope.row.status == 0 ? true : false"
                  type="danger"
                  @click="delet(scope.$index, scope.row.id)"
                  >取消</el-link
                >
                <el-link
                  style="color: rgb(17, 138, 178)"
                  @click="exportOrderiInfo(scope.row.id)"
                  >导出</el-link
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="main_page boxdq">
          <div></div>
          <!-- 分页 -->
          <div class="main_page_r">
            <MainPagination
              :current-page="current.page"
              :page-sizes="[20, 30, 50, 100]"
              :page-size="limit"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalCount"
              background
              @size-change="changeLimit"
              @current-change="changePage"
            />
          </div>
        </div>
      </div>
      <!-- 订单导入 -->
      <el-dialog
        title="盘点单导入"
        :visible.sync="importbuVisible"
        class="main_dialog dialog840 importbu"
        @close="importClose"
      >
        <div class="importbu_p">
          <h3>导入说明：</h3>
          <p>1.注意使用红色字体标注的必填字段,不填或错填将导致导入失败。</p>
          <p>2.导入文件仅支持xlsx格式,大小不超过2M ,数据不超过2000行。</p>
          <p>3.导入文件不能包含“合并单元格”，否则无法导入。</p>
          <p>
            4.导入时碰到数据不正确的行，系统会跳过错误的行继续执行未完成的行。
          </p>
        </div>
        <div class="importbu_an box">
          <el-button @click="downTemplate" v-repeatClick class="marginRight10"
            >下载模板</el-button
          >
          <el-upload
            class="upload-demo"
            :action="inventory_import"
            :on-success="importSuccess"
            :on-error="importerr"
            :headers="{
              Authorization: getToken(),
            }"
            :show-file-list="false"
            :data="import_params"
          >
            <el-button
              size="small"
              v-repeatClick
              @click="handleUpload"
              type="primary"
              >点击上传</el-button
            >
          </el-upload>

          <p v-if="import_file_name ? true : false">
            上传文件名：{{ import_file_name }}
          </p>
        </div>
        <div class="import_process" v-if="percentShow">
          <div class="progress">
            <el-progress
              :text-inside="true"
              :stroke-width="20"
              :percentage="percent"
              color="#19B098"
            ></el-progress>
          </div>
          <div class="notice" v-if="percentShow">
            <div class="importtips">
              <p class="success" v-if="percent == 100">盘点单导入结束</p>
              <div v-for="(item, index) in reverseSum" :key="index">
                <p v-if="item.type == 2" :key="index" class="fail">
                  {{ item.name }}，导入失败
                </p>
              </div>
            </div>
          </div>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button :disabled="cancelDisabled" @click="importbuVisible = false"
            >取 消</el-button
          >
        </div>
      </el-dialog>
      <!-- 盘点单导出 -->
      <ExportDialog :visible.sync="exportVisible" :statusList="list.statusList"></ExportDialog>
    </div>
  </div>
</template>

<script>
import { mixins } from "@/mixins/index.js";
import {
  inventorySheet_index,
  inventorySheet_cancel,
  inventorySheet_download,
  inventorySheetExport,
} from "@/api/warehouse/warehouseCheck";
import { inventory_import } from "@/api/currency";
import { apiUrl, objKeySort, Md5, packApi } from "@/utils/public";
import dateOption from "@/options/dateOption";
import { parseTime, exportMethod } from "@/utils/index";
import { mapGetters } from "vuex";
import ExportDialog from "@/views/warehouse/components/check/exportDialog.vue";

export default {
  mixins: [mixins],
  components: {
    ExportDialog
  },
  data() {
    return {
      // 时间
      parseTime,
      exportMethod,
      inventory_import,
      order_import: "",
      // 分页
      current: {
        page: 1,
        per_page: 20,
      },
      limit: 20,
      totalCount: 1,
      // 列表数据
      list: {
        list: [],
      },
      listLoading: false,
      // 搜索
      form: {
        order_sn: "",
        start_time: "",
        end_time: "",
      },
      createTime: [],
      pickerOptions: dateOption,
      // 订单导入
      importbuVisible: false,
      import_form: {
        start_line_num: 2,
        end_line_num: "",
      },
      import_file_name: "",
      import_params: {},
      percent_gs: 0,
      percent: 0,
      percentShow: false,
      percent_list: [],
      importArrLength: 1,
      cancelDisabled: false,
      exportVisible: false, // 盘点单导出弹框状态
    };
  },
  computed: {
    ...mapGetters(["userInfo", "avatar"]),
    reverseSum() {
      return this.percent_list;
    },
  },
  created() {
    // 列表
    this.getNumerical(160);
    this.inventorySheet_index();
  },
  mounted() {
    window.Echo.channel("importInventory." + this.avatar.company_id).listen(
      "ImportInentorySheet",
      (e) => {
        this.cancelDisabled = true;
        this.importArrLength = e.notice.count;
        this.percentShow = true;
        if (e.notice.code == 0) {
          this.percent_list.push({
            num: this.percent,
            type: 1,
            name: e.notice.msg,
          });
        } else if (e.notice.code == 100) {
          this.percent_list.push({
            num: this.percent,
            type: 2,
            name: e.notice.msg,
          });
        }
        this.percent_gs = parseInt(this.percent_gs) + 1;
        if ((this.percent_gs / this.importArrLength) * 100 >= 100) {
          this.percent = 100;
          this.cancelDisabled = false;
          return;
        }
        this.percent =
          this.percent_gs / this.importArrLength
            ? parseInt((this.percent_gs / this.importArrLength) * 100)
            : 0;
      }
    );
  },
  methods: {
    //  表格双击跳转详情页面
    rowDblclick(row, column, event) {
      this.$router.push('/warehouse/check/see/' + row.id)
    },
    reset() {
      this.$refs['userListFrom'].resetFields();
      this.createTime = [];
      this.inventorySheet_index()
    },
    // 点击回车键时调用搜索回调
    startGetting() {
      this.getArticleList();
    },
    // 搜索
    getArticleList() {
      this.current.page = 1;
      this.inventorySheet_index();
    },
    // 分页
    changeLimit(pageSize) {
      this.current.per_page = pageSize;
      this.inventorySheet_index();
    },
    changePage(page) {
      this.current.page = page;
      this.inventorySheet_index();
    },
    // 取消
    delet(index, id) {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, { id: id, type: 1 })) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { id: id, type: 1 }
      );
      this.$confirm("确定关闭盘点单?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          inventorySheet_cancel(data).then((res) => {
            if (res.errcode == 0) {
              this.$message({
                message: "取消成功",
                type: "success",
              });
              this.inventorySheet_index();
            } else {
              this.$message.error(res.errmsg);
            }
          });
        })
        .catch(() => {});
    },
    // 列表
    inventorySheet_index() {
      this.listLoading = true;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(
              Object.assign(apiUrl().name, this.list_form(), this.current)
            ) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        this.list_form(),
        this.current
      );
      inventorySheet_index(data).then((res) => {
        this.listLoading = false;
        if (res.errcode == 0) {
          this.list = res.data;
          this.totalCount = res.data.list.total;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    list_form() {
      let form = JSON.parse(JSON.stringify(this.form));
      form.start_time = this.createTime[0] ? this.createTime[0] : "";
      form.end_time = this.createTime[1] ? this.createTime[1] : "";

      return form;
    },
    // 导出盘点单
    exportCheck() {
      this.exportVisible = true;
    },
    // 入库单详情导出
    exportOrderiInfo(id) {
      let data = packApi({ id, list_headers: "0-1-2-3-4-5-6-7-8-9-10" });
      const notify = this.$notify.info({
        title: "开始导出...",
        type: "success",
        duration: 0,
      });
      inventorySheetExport(data).then((res) => {
        exportMethod(res, "库存盘点单", notify);
      }).catch(() => {
        this.$message.error("导出失败");
      });
    },

    // 下载模板
    downTemplate() {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name
      );
      const notify = this.$notify.info({
        title: "开始导出...",
        type: "success",
        duration: 0,
      });
      inventorySheet_download(data).then((res) => {
        this.exportMethod(res, "库存盘点导入模板", notify);
      });
    },
    // 导入盘点单
    importDialog() {
      this.import_file_name = "";
      this.percent_gs = 0;
      this.percent = 0;
      this.percentShow = false;
      this.percent_list = [];
      this.importArrLength = 1;
      this.cancelDisabled = false;
      this.importbuVisible = true;
    },
    importerr(err, file, fileList) {
      this.$message.error("上传失败");
    },
    importSuccess(response, file, fileList) {
      if (response.errcode != 0) {
        this.$message.warning(response.errmsg);
        return;
      }
      this.import_file_name = file.name;
    },
    handleUpload() {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { uid: this.userInfo.id }
      );
      this.import_params = data;
    },
    importClose() {
      if (this.percentShow) {
        this.getArticleList();
      }
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/styles/variables.scss";

.mainsu {
  .mainor_form form {
    width: calc(100% - 180px);
  }
}

// 支付状态
.success {
  color: $green;
}
.unpaid {
  color: $colour_red;
}
// 订单状态
.order0 {
  color: $order_color1;
}
.order1 {
  color: $order_color2;
}
.order2 {
  color: $order_color4;
}
.order3 {
  color: $order_color4;
}

.btn_big {
  width: 100px;
  padding: 10px;
}

// 导入进度条
.import_process {
  width: 100%;
}

.progress {
  padding: 15px 40px 15px 0;
  // display: flex;
  // justify-content: center;
  // align-items: center;
}
.notice {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  padding-right: 40px;
  .importtips {
    overflow-y: auto;
    width: 100%;
    height: 84px;
    height: 84px;
    background: #ffffff;
    border: 1px solid #d8d8d8;
    padding: 10px 15px;
    .fail {
      color: #ff5a5a;
      line-height: 1.2;
      font-size: 12px;
    }
    .success {
      color: #19b098;
      line-height: 1.2;
      font-size: 12px;
    }
  }
}

/deep/ .el-form-item--small.el-form-item {
  margin-bottom: 10px !important;
}
</style>
